<template>
	<view class="highlight">
		<uni-nav-bar v-if="!isDouyin" style="z-index:999;" height="80rpx" left-icon="left" @clickLeft="goBack" title="快拍"
			:fixed="true" :statusBar='!isDouyin'></uni-nav-bar>
		<view class="video-image-container">
			<image v-show="isVideo !== true" :class="[img1 ? 'img1' : '', 'opacity']" :src="curryUrl" mode="aspectFill"
				@load="imageLoad"></image>
			<image v-show="isVideo !== true" :class="[img2 ? 'img2' : '', 'opacity']" :src="nextUrl" mode="aspectFill"
				@load="imageLoad"></image>
			<video v-show="isVideo === true" :autoplay="true" :src="videoUrl" :show-fullscreen-btn="false"
				:show-bottom-progress="false" :enable-progress-gesture="false" :show-center-play-btn="false"
				:show-play-btn="false" @play="imageLoad" :show-progress="false" :show-mute-btn="false" :http-cache="true"
				:muted="true" objectFit="fill"></video>
		</view>
		<view class="progress-list" :style="{ 'top': topHeight + 'px' }">
			<view class="progress" v-for="(item, index) in items" :key="index">
				<view class="process-bottom"></view>
				<view class="process-top" :style="{ width: item.style.width }"></view>
			</view>
		</view>
		<view class="hightlight-title" :style="{ 'top': topHeight + 10 + 'px' }">
			<u-avatar :src="avgurl"></u-avatar>
			<text class="white">{{ title }}</text>
			<text class="white">{{ times }}</text>
		</view>
		<view class="hightlight-util">
			<!-- 			<u-icon name="heart" color="#fff" size="28"></u-icon>
			<u-icon name="share-square" color="#fff" size="28"></u-icon> -->
			<u-button size="mini" text="保存" type="primary" @click="saveFile"></u-button>
			<u-button size="mini" text="分享" type="error" @click="share"></u-button>
		</view>
		<view class="hightlight-util" style="bottom: 30rpx;">
			<ad-custom unit-id="adunit-a542e42550500ee9" v-if="!isVipExpired"></ad-custom>
		</view>
	</view>
</template>

<script>
import Config from "@/common/config.js";
import { getDetailStore } from "@/api/app/api.js"
import {
	transformTime
} from "@/utils/utils.js";
export default {
	data() {
		return {
			title: "",
			videoUrl: "",
			times: "",
			curryIndex: 0,
			items: [],
			mediaCount: 0,
			isNext: false,
			nextUrl: "",
			curryUrl: "",
			timer: "",
			item: "",
			nextType: "",
			isRuning: false,
			isVideo: false,
			isDouyin: false,
			topHeight: 0,
			imgCount: 0,
			avgurl: ""
		};
	},
	methods: {
		play(val) {
			let id = null;
			let isComplite = false;
			let item = val;
			if (this.items[this.curryIndex + 1]?.media_type != 2) {
				if (this.isNext) {
					this.curryUrl = this.items[this.curryIndex + 1]?.url;
					console.log('this.curryUrl:', this.curryUrl)
				} else {
					this.nextUrl = this.items[this.curryIndex + 1]?.url;
					console.log('this.nextUrl:', this.nextUrl)
				}
			}
			if (item === undefined) {
				return;
			}
			this.timer = setInterval(() => {
				let width = item.style.width.replace("%", "");
				width = Number(width) + 100 / item.duration;
				if (width >= 100) {
					item.style.width = "100%";
					isComplite = true;
				} else {
					item.style.width = width + "%";
				}
				if (isComplite) {
					this.curryIndex = this.curryIndex + 1;
					if (this.curryIndex >= this.items.length) {
						return
					}
					if (this.isNext) {
						this.isNext = false;
					} else {
						this.isNext = true;
					}
					if (this.nextType === "image") {
						this.isVideo = false;
						this.item = this.items[this.curryIndex];
					} else {
						console.log('isVideo', this.items[this.curryIndex].url)
						this.isVideo = true;
						this.videoUrl = this.items[this.curryIndex].url;
						this.item = this.items[this.curryIndex]
					}
					clearInterval(this.timer);
				}
			}, 1000);
		},
		imageLoad(event) {
			if (!this.isRuning) {
				// 第一次触发
				this.item = this.items[this.curryIndex];
				this.isRuning = true;
			}
			let nextItem = this.items[this.curryIndex + 1];
			console.log(nextItem, nextItem?.media_type == 2)
			// 如果正在播放的是isNext的视频，那么就要去处理curryUrl的赋值
			if (nextItem && nextItem.media_type != 2) {
				this.nextType = "image";
			} else if (nextItem && nextItem.media_type == 2) {
				this.nextType = "video";
			}
			//  2 1 1
			// console.log('images',this.curryIndex,this.items[this.curryIndex].media_type,nextItem.media_type,this.nextType)
		},
		nextStart() {
			this.isNext = true;
		},
		goBack() {
			// uni.navigateBack({
			// 	animationType: "auto",
			// 	animationDuration: 1,
			// });
			uni.switchTab({
				url: "/pages/home/home-list"
			})
		},
		saveFile() {
			this.items.forEach((item, index) => {
				try {
					this.downloadFile(item.url, index)
				} catch (e) {
					console.log('err', e)
				}
			})
		},
		downloadFile(id, index) {
			if(this.$store.getters.getVipExpired){
				console.log(id, index, this.items);
				let types = id.split('.');
				uni.downloadFile({
					url: id,
					success: (res) => {
						console.log('res', res)
						types[types.length - 1] == 'mp4' ?
							wx.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath
							}) :
							wx.saveImageToPhotosAlbum({
								filePath: res.tempFilePath
							})
						if (index === this.items.length - 1) {
							uni.hideLoading()
							uni.showToast({
								title: "保存成功",
								icon: 'success',
								duration: 1000
							})
						}
					},
					fail: (err) => {
						console.log(err)
						uni.hideLoading()
						uni.showToast({
							title: "保存失败",
							icon: 'error',
							duration: 1000
						})
					}
				})
			}else{
				wx.showModal({
					title:"温馨提示",
					content:"您还不是会员,是否开通会员?",
					success(){
						wx.navigateTo({
							url:"/pages/personal/pay"
						})
					},
					fail(){
						
					},
				})
			}
		},
		share() {
			wx.downloadFile({
				url: ""
			})
			wx.showShareImageMenu()
		}
	},
	watch: {
		item(newVal, oldVal) {
			// console.log('item:',newVal,oldVal)
			if (newVal != undefined) {
				if (newVal.media_type == 2) {
					this.isVideo = true;
					this.videoUrl = newVal.url;
				}
				this.play(newVal);
			}
		},
	},
	computed: {
		img2() {
			return this.isVideo === false && this.isNext == true;
		},
		img1() {
			return this.isVideo === false && this.isNext == false;
		},
		isVipExpired(){
			console.log('$store.getters.getVipExpired', this.$store.getters.getVipExpired)
			return this.$store.getters.getVipExpired
		}
	},
	onShareTimeline() {

	},
	onShareAppMessage() {

	},
	onLoad(options) {
		// #ifdef MP-WEIXIN
		let interstitialAd11 = wx.createInterstitialAd({
			adUnitId: 'adunit-af52896212f94e7b'
		});
		interstitialAd11.onLoad(() => { })
		interstitialAd11.onError((err) => { })
		interstitialAd11.onClose(() => { })
		interstitialAd11.show().catch((err) => {
			console.error(err)
		})
		// #endif
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
		this.isDouyin = this.$store.getters.getsysteminfo.uniPlatform == 'mp-toutiao';
		this.topHeight = (40 * (this.$store.getters.getsysteminfo.screenWidth / 375)) + this.$store.getters.getsysteminfo.statusBarHeight + 5;
		console.log('options', options)
		if (options.issub) {
			let mediaid = options.mediaid;
			getDetailStore({
				mediaid: mediaid
			}).then(res => {
				uni.hideLoading();
				let datas = res.data[0];
				this.title = datas.title || this.$store.getters.getUserInfo.username;
				this.times = transformTime(datas.created_at || datas.expiring_at);
				this.mediaCount = datas.media_count;
				this.avgurl = Config.base_Url + "ins_img/" + datas.user.username + 'HeadPortrait.jpg'
				datas.items.forEach((item, _index) => {
					let href =
						item.media_type === 1 ?
							Config.static_url + 'ins_img/' + `${item.pk}.jpg` :
							Config.static_url + 'ins_img/' + `${item.pk}.mp4`;
					this.items.push({
						url: href,
						style: {
							width: "0%",
						},
						media_type: item.media_type,
						duration: item.media_type == 2 ? item.video_duration ?? item.duration : item.duration ?? 5,
					});
					if (_index === 0) {
						item.media_type == 1 ?
							(this.curryUrl = href) :
							(this.videoUrl = href);
						item.media_type == 1 ? (this.isVideo = false) : (this.isVideo = true);
					}
				});
			}).catch(err => {
				console.log(err)
			})
		} else {
			let channel = this.getOpenerEventChannel();
			channel.on("videoChannel", (res) => {
				let datas = res.data;
				console.log(datas);
				this.title = datas.title || this.$store.getters.getUserInfo.username;
				this.times = transformTime(datas.created_at || datas.expiring_at);
				this.mediaCount = datas.media_count;
				this.avgurl = Config.base_Url + "ins_img/" + datas.user.username + 'HeadPortrait.jpg'
				datas.items.forEach((item, _index) => {
					let href =
						item.media_type === 1 ?
							Config.static_url + 'ins_img/' + `${item.pk}.jpg` :
							Config.static_url + 'ins_img/' + `${item.pk}.mp4`;
					this.items.push({
						url: href,
						style: {
							width: "0%",
						},
						media_type: item.media_type,
						duration: item.media_type == 2 ? item.video_duration ?? item.duration : item.duration ?? 5,
					});
					if (_index === 0) {
						item.media_type == 1 ?
							(this.curryUrl = href) :
							(this.videoUrl = href);
						item.media_type == 1 ? (this.isVideo = false) : (this.isVideo = true);
					}
				});
			}
			);
		}
	},
	beforeDestroy() {
		clearInterval(this.timer);
	},
};
</script>

<style lang="scss" scoped>
.highlight {
	display: flex;
	flex-direction: column;
	width: 100vw;
	height: 100vh;
}

.white {
	color: #fff;
}

.hightlight-title {
	position: absolute;
	display: flex;
	left: 20rpx;
	column-gap: 15rpx;
	align-items: center;
	margin-top: 15rpx;
	z-index: 1001;
}

.video-image-container {
	flex: 1;

	image,
	video {
		width: 100%;
		height: 100%;
		position: relative;
	}
}

.opacity {
	display: none;
}

.img1 {
	display: block;
}

.img2 {
	display: block;
}

$process-height: 8rpx;

.progress-list {
	display: flex;
	column-gap: 8rpx;
	position: absolute;
	z-index: 1000;
	left: 0;
	right: 0;
	padding-left: 1.5%;


	.progress {
		flex: 1;
		position: relative;
		height: $process-height;

		.process-bottom {
			position: absolute;
			width: 100%;
			background-color: rgba(255, 255, 255, 0.35);
			height: $process-height;
			z-index: 998;
		}

		.process-top {
			position: absolute;
			width: 0%;
			transition: width 1s linear;
			will-change: width;
			background-color: #fff;
			height: $process-height;
			z-index: 999;
		}
	}
}

.hightlight-util {
	position: absolute;
	bottom: 260rpx;
	right: 25rpx;
	display: flex;
	flex-direction: column;
	row-gap: 10rpx;
	column-gap: 10rpx;
	z-index: 1002;
}</style>